package cn.yeziji.forum.factory.websocket.parts;

import cn.yeziji.forum.common.key.WebsocketCacheKey;
import cn.yeziji.forum.common.websocket.Chatroom;
import cn.yeziji.forum.dao.intf.ForumChatroomDao;
import cn.yeziji.forum.entity.ForumChatroomEntity;
import cn.yeziji.forum.exception.ChatroomException;
import cn.yeziji.forum.factory.websocket.WebsocketOperationAbstract;
import cn.yeziji.forum.factory.websocket.WebsocketOperationExecutioner;
import cn.yeziji.forum.factory.websocket.WebsocketOperationInterface;
import cn.yeziji.forum.factory.websocket.enums.WebsocketFactoryOption;
import cn.yeziji.forum.common.enums.status.ChatroomStatus;
import cn.yeziji.forum.utils.JwtOperaUtils;
import cn.yeziji.forum.utils.ListsCollect;
import cn.yeziji.forum.vo.chatroom.UserMsgStatisticVO;
import com.github.benmanes.caffeine.cache.Cache;

import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 用户聊天信息
 *
 * @author gzkemays
 * @since 2022/4/1 8:44
 * @deprecated to netty
 */
public class UserChatMsgPart extends WebsocketOperationAbstract<Chatroom>
    implements WebsocketOperationInterface {

  public UserChatMsgPart(Object data) {
    super(data);
  }

  @Override
  protected Object defaultMethod() {
    Integer userId = tokenCheck();
    ForumChatroomDao chatroomDao = getChatroomDao();
    Cache<String, String> userCache = getUserCache();
    // 建立以 userId 作为键值的用户的 token 令牌缓存
    userCache.put(userId.toString(), params.getToken());
    List<UserMsgStatisticVO> userMsgByUserId = chatroomDao.getUserMsgByUserId(userId);
    send(params.getToken(), userMsgByUserId, JSON_ARRAY);
    return userMsgByUserId;
  }

  @Override
  public Object operation(WebsocketFactoryOption option) {
    return invoke(getClass(), option);
  }

  public void userRecords() {
    tokenCheck();
    if (params.getKey().equals(Chatroom.USER_RECORDS)) {
      ForumChatroomDao chatroomDao = getChatroomDao();
      params.reBuildChatroomName();
      String chatroom = params.getChatroom();
      List<ForumChatroomEntity> chatroomRecords = chatroomDao.getChatroomRecords(chatroom, false);
      // 用户获取聊天记录后，让在 redis 过期将聊天记录更新。
      WebsocketOperationExecutioner.execute(
          WebsocketFactoryOption.CHAT_ROOM_EXPIRED,
          params,
          WebsocketCacheKey.privateChatroom(chatroom));
      List<ForumChatroomEntity> collect =
          chatroomRecords.stream()
              .filter(chat -> Objects.isNull(chat.getUpdateTime()))
              .peek(chat -> chat.setUpdateTime(new Date()))
              .collect(Collectors.toList());
      ListsCollect.of(collect).notEmptyConsumer(chatroomDao::batchSave);
      // 发送消息
      send(params.getToken(), chatroomRecords, JSON_ARRAY);
    }
  }

  /**
   * 检查token
   *
   * @return 用户 id
   */
  private Integer tokenCheck() {
    String token = params.getToken();
    if (token == null) {
      throw new ChatroomException(ChatroomStatus.THIS_WEBSOCKET_LINK_NOT_POWER);
    }
    Integer userId = JwtOperaUtils.getIdByToken(token);
    if (userId == null) {
      throw new ChatroomException(ChatroomStatus.USER_ID_NOT_FOUND);
    }
    return userId;
  }
}
